package com.example.webbrowser.Fragment;

import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
;

import com.example.webbrowser.Database.BookMarkManager;
import com.example.webbrowser.Adapter.MarkAdapter;
import com.example.webbrowser.Entity.MarkDialog;
import com.example.webbrowser.Entity.MarkListView;
import com.example.webbrowser.MainActivity;
import com.example.webbrowser.R;
import com.example.webbrowser.WebViewActivity;
import com.google.android.material.tabs.TabLayout;

import java.util.List;


public class BookMarkFragment extends Fragment {
    private String TAG = "BookMarkFragment";
    private BookMarkManager bookMarkManager;
    private ListView lv;
    private boolean isFirstLoading = true;
    Point point = new Point();
    private MarkDialog MyDialog;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bookmark,container,false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        //new BookMarkManager().initMark(getActivity());
        bookMarkManager = new BookMarkManager(getActivity());
        Button button = getActivity().findViewById(R.id.Markbutton);
        Button inputViewButton = getActivity().findViewById(R.id.addMark);
        button.setOnClickListener(onClickListener);
        inputViewButton.setOnClickListener(onClickListener);

        //bookMarkManager.addFavorite("百度","www.baidu.com");

        lv=(ListView)getActivity().findViewById(R.id.ListView_Mark);
        List<MarkListView> allMark = bookMarkManager.getAllFavorites();
        lv.setAdapter(new MarkAdapter(allMark, getActivity()));
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                // TODO Auto-generated method stub
                String url = allMark.get(position).url;
                Log.d(TAG,"单击事件"+",参数："+url);
                //int i = bookMarkManager.getId(url);
                Intent intent = new Intent(getActivity(),WebViewActivity.class);
                bookMarkManager.getId(url);
                intent.putExtra("web_url",url);
                startActivity(intent);
            }
        });

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                MarkListView data = allMark.get(position);
                System.out.println("长按事件"+data.toString());

                PopupMenu popup = new PopupMenu(getActivity(), view);
                //获取菜单
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.layout.popup_window, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.long_delete:
                                bookMarkManager.deleteFavorite(data.id);
                                updataListView();
                                break;
                            case R.id.long_modify:
                                Log.d(TAG,"长按——修改事件");
                                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                                dialog.setTitle("修改书签");
                                // 取得自定义View
                                LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                                final View myLoginView = layoutInflater.inflate(
                                        R.layout.bookmark_inputview, null);
                                dialog.setView(myLoginView);
                                EditText loginAccountEt = (EditText) myLoginView
                                        .findViewById(R.id.my_login_account_et);
                                EditText loginPasswordEt = (EditText) myLoginView
                                        .findViewById(R.id.my_login_password_et);

                                loginAccountEt.setText(data.getName());
                                loginPasswordEt.setText(data.getUrl());

                                loginAccountEt.setSelection(data.getName().length());
                                loginPasswordEt.setSelection(data.getUrl().length());

                                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        if(bookMarkManager.modifyFavorite(data.getId(),loginAccountEt.getText().toString(),
                                                loginPasswordEt.getText().toString())){
                                            Log.d("MyLogin Dialog","输入框修改书签成功");
                                            updataListView();
                                        }else{
                                            Log.d("MyLogin Dialog","输入框修改书签失败");
                                        }
                                    }
                                });

                                dialog.setNegativeButton("取消",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        });
                                dialog.show();
                                break;

                        }
                        return false;
                    }
                });
                popup.show();
                //showPopupWindow(getActivity(),view);
                return true;
            }
        });



    }
    public class MarkPopupWindow extends PopupWindow {

        public MarkPopupWindow(Context context) {
            super(context);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            setOutsideTouchable(true);
            setFocusable(true);
            setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            setWidth(100);
            setHeight(100);

            View contentView = LayoutInflater.from(context).inflate(R.layout.popup_window,
                    null, false);
            setContentView(contentView);
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.Markbutton:
                    MyDialog.show(getActivity(), "确定删除全部书签吗?", new MarkDialog.OnConfirmListener() {

                        @Override
                        public void onConfirmClick() {
                            bookMarkManager.initMark(getActivity());
                            Log.d("BookMarkFragment","初始化成功");
                            //showAllMark();
                            updataListView();
                            //这里写点击确认后的逻辑
                        }
                    });
                    break;
                case R.id.addMark:
                    // 6、自定义View的AlertDialog
                    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                    dialog.setTitle("添加新书签");
                    // 取得自定义View
                    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                    final View myLoginView = layoutInflater.inflate(
                            R.layout.bookmark_inputview, null);
                    dialog.setView(myLoginView);

                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EditText loginAccountEt = (EditText) myLoginView
                                    .findViewById(R.id.my_login_account_et);
                            EditText loginPasswordEt = (EditText) myLoginView
                                    .findViewById(R.id.my_login_password_et);
                            if(bookMarkManager.addFavorite(loginAccountEt.getText().toString(),
                                    loginPasswordEt.getText().toString())){
                                Log.d("MyLogin Dialog","输入框添加书签成功");
                                updataListView();
                            }else{
                                Log.d("MyLogin Dialog","输入框添加书签失败");
                            }
                        }
                    });

                    dialog.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                    dialog.show();
                    break;
            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //finish();
                break;
        }
        return true;
    }


    /**
     * 在fragment可见的时候，刷新数据
     */
    @Override
    public void onResume() {
        super.onResume();

        if (!isFirstLoading) {
            //如果不是第一次加载，刷新数据
            lv=(ListView)getActivity().findViewById(R.id.ListView_Mark);
            lv.setAdapter(new MarkAdapter(bookMarkManager.getAllFavorites(), getActivity()));
        }
        isFirstLoading = false;
    }

    public void updataListView(){
        lv=(ListView)getActivity().findViewById(R.id.ListView_Mark);
        lv.setAdapter(new MarkAdapter(bookMarkManager.getAllFavorites(), getActivity()));
    }

    // 实现回调接口，定义触摸后的操作
    private MainActivity.MyTouchListener myTouchListener = new MainActivity.MyTouchListener() {

        @Override
        public void onTouch(MotionEvent ev) {
            switch (ev.getAction()) {
                // 手指点击屏幕时，记录当前的X坐标和Y坐标
                case MotionEvent.ACTION_DOWN:
                    point.x = (int) ev.getX();
                    point.y = (int) ev.getY();
                    Log.d("MotionEvent","鼠标位置"+point.x+"和"+point.y);
                    break;
            }
        }

    };
}